const router=require('koa-router')()
const fs=require('fs')

function getRouterFile(filePath){
 let temPath=filePath || __dirname;
 let files=fs.readdirSync(temPath);
 let routerfile=files.filter(item=>{
     return item.endsWith('.js') && item!='routes.js'
 })
 return routerfile;
}

function registryRouter(router,routerfile){
    routerfile.forEach(item=>{
        let temPath=__dirname + "/" +item;
        let obj=require(temPath);
        for(let key in obj){
            let temArr=key.split(' ');
            let rMethood=temArr[0];
            let rPath=temArr[1];
            let rFunction=obj[key];
            if(rMethood==='get'){
                router.get(rPath,rFunction)
            }else if(rMethood==='post'){
                router.post(rPath,rFunction)
            }else if(rMethood==='put'){
                router.put(rPath,rFunction)
            }else if(rMethood==='delete'){
                router.delete(rPath,rFunction)
            }else{
                console.log('错误路径！');
            }
        }
    })
    return router.routes()
}

module.exports=function(){
    let routerfile=getRouterFile();
    let fn=registryRouter(router,routerfile);
    return fn;
}